/*
Our raw data covers: 
1) The 1980-2012 period for GDP, Debt, and Consumption
2) The 1993.Dec-2012.Dec period for Sovereign Spreads and Trade Balance

Notes - Construction of Moments
1) Argentina defaulted in 1982 and regained access in 1993.q2. No spreads available prior 1993.
2) Argentina defaulted in 2001 and regained access in 2005. We exclude those periods when computing spreads and external debt.
3) For spreads, we also exclude the period of the GFC. We would need a shock to lenders' SDF to better explain this period.
4) When computing the GDP trend and cycle, we account for a break in trend in 2001.
*/


clear all
cls
local path_rawdata = "00_data/00_raw_data"
local path_inputs  = "00_data/01_datasets/00_inputs"
local path_output  = "00_data/02_output"


*------------------------------------------------------------------------------
* Choose samples for main analysis
*------------------------------------------------------------------------------
* Break for GDP trend
	local breakTrend_GDP = 2001

* Sample period for spreads
	local sample_spreads = "(qDate>=q(1993q4) & qDate<=q(2001q2) | qDate>=q(2005q4)) & qDate<=q(2008q1)"

* Sample period for GDP
	local sample_GDP     = "qDate>=q(1980q1) & qDate<=q(2012q4)  &  (qDate<q(1981q4) | qDate>q(1983q4) )  &  (qDate<=q(2001q2) | qDate>q(2003q4) ) "  

* Sample period Debt
	local sample_debt    = "(  Year>=1993 & (Year<=2001|Year>=2005)   & Year<=2007 )" 
*------------------------------------------------------------------------------
	
	
/// ------------------------------------------------------------------------------------------------ ///
/// -----------------------------------   COMPUTE TARGETED MOMENTS---------------------------------- ///
/// ------------------------------------------------------------------------------------------------ ///

*** Import Argentine Sovereign Spreads (EMBI, diversified, stripped)
*-----------------------------------------------------------------------------------
import excel "`path_rawdata'/00_EMBI_Index.xls", sheet("EMBI") cellrange(A1:B7497) firstrow clear
	rename EMBI_ARG Spread
	drop if Spread==.
	qui gen qDate = yq(year(Date), quarter(Date))
	format qDate %tq
	drop Date
	collapse (mean) Spread, by(qDate)
	qui gen Year = year(dofq(qDate))

	* Export Quarterly Spreads for Argentine counterfactual [to be uploaded in the quantitative analysis]
	preserve
		keep if Year>=2006 & Year<=2012
		export delimited Spread using "`path_output'/ARG_EMBI_quant.csv", novarnames replace
	restore

	* Compute Average Spread and Time Series Volatility [targeted moments]
		keep if `sample_spreads'
		tab qDate
		sum Spread
		local avg_SP = r(mean)
		local sd_SP  = r(sd)

	* Save [used for correlations below]
	save "`path_inputs'/spread_Q.dta", replace


*** Import Argentine Debt/GDP and compute averagege debt-to-GDP ratio
*-----------------------------------------------------------------------------------
import excel "`path_rawdata'/01_Arg_Debt.xls", firstrow cellrange(A5:D52) clear
	keep Year Debtratio
	rename Debtratio Debt
	sum Debt if `sample_debt'
	local avg_debt = r(mean)
	

*** Import data on national accounts
*-------------------------------------------------------------------------------
import excel "`path_rawdata'/01_Arg_NationalAccounts.xls", sheet("NACC") firstrow clear
keep Date GDP CTOT EXP IMP
gen Year  = yofd(Date)
gen qDate =qofd(Date)
format qDate %tq
drop Date
sort qDate
qui gen time = _n
tsset time


*** Compute Trend & Cycle of Variables [allow for break at Year=`breakTrend_GDP']
*--------------------------------------------------------------------------------
local var_list   = "GDP CTOT"
qui gen dumT     = 0
qui replace dumT = 1 if  Year<=`breakTrend_GDP'
foreach var_v of local var_list {
	*Log Linear Trend
		gen ln`var_v' = ln(`var_v')
		reg ln`var_v' i.dumT##c.time
		predict `var_v'_LLcycle, residuals
}
label variable GDP_LLcycle "GDP LL Cycle"

* Keep Relevant data
keep if `sample_GDP'
tab Year

* Estimate rho_y and sigma_y [AR1 parameters]
*-----------------------------------------------------------------------------------
reg GDP_LLcycle L1.GDP_LLcycle
local rho_Y = _b[L1.GDP_LLcycle]
predict resid, resid
qui sum resid
local sd_eY = r(sd)
drop resid
	
	 
/// ------------------------------------------------------------------------------------------------ ///
/// --------------------------------------  COMPUTE UNTARGETED MOMENTS  ----------------------------- ///
/// ------------------------------------------------------------------------------------------------ ///  

* Default probability (historical data - see paper for details)
local def_prob = 3.333/100
	  
* Generate trade balance
qui gen TB = (EXP - IMP)/GDP


*** Merge with dataset on sovereign spreads (for correlations)
sort qDate
merge 1:1 qDate using "`path_inputs'/spread_Q.dta"
drop if _merge==2
drop _merge
erase "`path_inputs'/spread_Q.dta"


*** Volatilities and correlations of other variables

* S.D. of cycle of variables and of TB
*-------------------------------------
qui sum GDP_LLcycle
	local sd_GDP = r(sd)
qui sum CTOT_LLcycle
	local sd_CTOT = r(sd)
qui sum TB
	local sd_TB = r(sd)

* Relative S.D.
*-------------------------------------
local rel_sd_CTOT = `sd_CTOT' / `sd_GDP'
local rel_sd_TB   = `sd_TB' / `sd_GDP'

* Correlations
*-------------------------------------
qui correlate CTOT_LLcycle GDP_LLcycle
	local corr_CTOT = r(rho)
correlate TB GDP_LLcycle
	local corr_TB = r(rho)
correlate Spread GDP_LLcycle
	local corr_SP = r(rho)


/// ------------------------------------------------------------------------------------------------ ///
* Export targeted & untargeted moments [to be uploaded in the quantitative analysis]
/// ------------------------------------------------------------------------------------------------ ///
qui gen mm_name = ""
qui gen mm_val  = .
*                        1             2          3        4       5        6       7          8       9
local list_export = "rel_sd_CTOT   corr_CTOT  rel_sd_TB corr_TB  avg_SP   sd_SP   corr_SP  def_prob  avg_debt"
local ii = 0
foreach var_v of local list_export {
	local ii = `ii' + 1
	qui replace mm_name = "`var_v'" 	if _n==`ii'
	qui replace mm_val  = ``var_v'' 	if _n==`ii'
}
export delimited mm_val using "`path_output'/targets_out.txt", delimiter(tab) novarnames replace




/// ------------------------------------------------------------------------------------------------ ///
/// -----------------------------  COMPUTE CYCLES FOR COUNTERFACTUALS  ----------------------------- ///
/// ------------------------------------------------------------------------------------------------ ///
preserve
	keep qDate GDP_LLcycle
	order qDate GDP_LLcycle
	save "`path_inputs'/GDPcycle_Q.dta", replace
restore

* Save series of GDP cycle [to be uploaded in the quantitative analysis]
preserve
	keep if (qDate>=q(2006q1) & qDate<=q(2012q4))
	export delimited GDP_LLcycle CTOT_LLcycle using "`path_output'/GDPcyc_ARG.csv", novarnames replace
restore


/// ------------------------------------------------------------------------------------------------ ///
/// --------------------------------  MOMENTS FOR INFLATION MISREPORT  ----------------------------- ///
/// ------------------------------------------------------------------------------------------------ ///  
*** Export path of misreport
use "`path_inputs'/01_Arg_Inflation.dta", clear
keep  year Measured_Month Inf_Misreport
keep if year>=2006 & year<=2012
gen quarter = quarter(dofm(Measured_Month))

* Collapse at quarterly frequency [to be uploaded in the quantitative analysis]
collapse (sum) Inf_Misreport, by(year quarter)
export delimited Inf_Misreport using "`path_output'/InfMisreport_Series.txt", delimiter(tab) novarnames replace


*** Compute some moments for the misreport, BE, and spreads
use "`path_inputs'/03_BreakEvenInflation.dta", clear
keep Date EMBI_ARG Inf_Misreport Inf_Misreport_Change BE

qui gen qDate = qofd(Date)
format qDate %tq

global window_type=0

qui sort Date
qui gen date_id = _n
qui sort date_id
qui tset date_id

qui gen BE_Change   = (BE-L.BE)
qui gen EMBI_ARG_Change   = 100*(ln(EMBI_ARG)-ln(L.EMBI_ARG))


qui sort date_id
merge m:1 qDate using "`path_inputs'/GDPcycle_Q.dta"
drop if _merge==2
drop _merge
erase "`path_inputs'/GDPcycle_Q.dta"


qui sort date_id


/// ------------------------------------------------------------------------------------------------ ///
/// -------------------------  HIGH-FREQ MOMENTS FOR BE & INFLATION MISREPORT  --------------------- ///
/// ------------------------------------------------------------------------------------------------ ///  

*** Create windows
do "01_codes/00_CreateWindows_fx.do"

*** Average of Delta Misreport and Delta Spread within window
bysort EVENT_ID: egen dMisrepWind = max(Inf_Misreport_Change)
qui replace dMisrepWind = . if in_window==0
bysort EVENT_ID: egen dEMBIWind = mean(EMBI_ARG_Change)
qui replace dEMBIWind = . if in_window==0
bysort EVENT_ID: egen dBEWind = mean(BE_Change)
qui replace dBEWind = . if in_window==0
sort date_id

qui replace dMisrepWind=. if Inf_Misreport==.
qui replace dEMBIWind=.  if Inf_Misreport==.
qui replace dBEWind=.    if Inf_Misreport==.


* Correlations
* Spread and Misreport (variations)
correlate dMisrepWind dEMBIWind if in_window==1 & Date>=d(01jan2007)  & Date<=d(01mar2008)
scalar cr_dpi_dSP = r(rho)

* Break-even and Misreport (variations)
correlate dMisrepWind dBEWind if in_window==1 & Date>=d(01jan2007)  & Date<=d(01mar2008)
scalar cr_dpi_dBE = r(rho)

qui gen Year = year(Date)
format Year %ty

*Moments for inflation misreport
sum Inf_Misreport if (Date>=d(01jan2007)  & Date<=d(01mar2008))
scalar avg_pi = r(mean)*3 // quarterly rate (as in model)
scalar std_pi = r(sd)*3   // quarterly rate (as in model)

*Collapse at quarterly frequency
collapse (mean) Inf_Misreport GDP_LLcycle Year, by(qDate)
sort qDate
tsset qDate
qui gen Inf_Misreport_Change = Inf_Misreport - L1.Inf_Misreport
correlate Inf_Misreport GDP_LLcycle if Year>=2007
scalar cr_pi_dY = r(rho)

* Export results [to be uploaded in the quantitative analysis]
mat outmms = [avg_pi\std_pi\cr_dpi_dSP\cr_dpi_dBE\cr_pi_dY]
svmat outmms
export delimited outmms using "`path_output'/piBE_out.txt", delimiter(tab) novarnames replace

